package com.lc.controller;

import com.github.pagehelper.PageInfo;
import com.lc.bean.Supplier;
import com.lc.service.SupplierService;
import com.lc.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    SupplierService supplierService;


//    @RequestMapping("/list")
//    public String list(Model model) {
//        List<Supplier> all = supplierService.findAll();
//        model.addAttribute("all",all);
//        return "supplier-list";
//    }

    // 添加商品类型使用的，下拉列表数据
    @GetMapping("/list")
    @ResponseBody
    public R listSelectOptionItem() {
        List<Supplier> ss = supplierService.selectOptionItems();
        return R.ok(ss);
    }

    @RequestMapping("/save")
    public String save(Supplier supplier) {
        supplierService.save(supplier);
        // 刷新数据，重定向
        return "redirect:/supplier/findByConditions";
    }

    // 根据id删除数据
    @RequestMapping("/del/{uuid}")
    public String del(@PathVariable("uuid") Integer uuid) {
        supplierService.del(uuid);
        // 刷新数据
        return "redirect:/supplier/findByConditions";
    }

    // 点击编辑链接
    // 1、根据id查询到详细数据
    // 2、设置到域中
    // 3、在jsp页面回显数据
    @RequestMapping("/toEdit")
    public String toEdit(Integer uuid,Model model) {
        Supplier supplier = supplierService.findById(uuid);
        model.addAttribute("supllier",supplier);
        return "supplier-update";
    }

    // 提交更新
    @PostMapping("/update")
    public String update(Supplier supplier) {
        supplierService.update(supplier);
        return "redirect:/supplier/findByConditions";
    }


    @RequestMapping("/findByConditions")
    public String findByConditions(Supplier supplier,
                                   Model model,
                                   String type,
                                   @RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "3") Integer pageSize) {

        // 表示使用js提交的表单，不是点击提交按钮
        if(!"auto".equals(type)) {
            pageNum = 1;
        }

        PageInfo<Supplier> pageInfo = supplierService.findByConditions(supplier, pageNum, pageSize);



        // 列表数据
        model.addAttribute("all",pageInfo.getList());
        // 搜索条件回显
        model.addAttribute("sup",supplier);
        // 把PageInfo设置到域中
        model.addAttribute("pageInfo",pageInfo);

        return "supplier-list";
    }
}
